package com.rivues.module.manage.web.handler.account;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.eigenbase.xom.MetaDef.Model;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.rivues.core.RivuDataContext;
import com.rivues.module.manage.web.service.AccountService;
import com.rivues.module.platform.web.exception.BusinessException;
import com.rivues.module.platform.web.handler.Handler;
import com.rivues.module.platform.web.handler.RequestData;
import com.rivues.module.platform.web.handler.ResponseData;
import com.rivues.module.platform.web.interceptor.LogIntercreptorHandler;
import com.rivues.module.platform.web.model.Organ;
import com.rivues.module.platform.web.model.User;
import com.rivues.module.platform.web.model.UserOrgan;
import com.rivues.module.platform.web.model.UserRole;
import com.rivues.module.report.web.model.PublishedReport;
import com.rivues.util.RivuTools;
import com.rivues.util.exception.ReportException;
import com.rivues.util.iface.authz.UserAuthzFactory;
import com.rivues.util.iface.report.ReportFactory;
import com.rivues.util.local.LocalTools;
import com.rivues.util.service.cache.CacheHelper;
  
@Controller  
@RequestMapping("/{orgi}/manage/account")  
public class AccountController extends Handler{
	private final Logger logger = LoggerFactory.getLogger(AccountController.class);
    @RequestMapping(value="/index" , name="index" , type="manage",subtype="account")
    public ModelAndView index(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data) throws Exception{ 
    	ModelAndView modelView = request(super.createManageTempletResponse("/pages/manage/account/index") , orgi) ;
    	modelView.addObject("organList", super.getService().findAllByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("orgi",orgi)))) ;
//    	modelView.addObject("userorganList", super.getService().findAllByCriteria(DetachedCriteria.forClass(UserOrgan.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("organid","0")))) ;
    	String clazz = (String) CacheHelper.getDistributedDictionaryCacheBean().getCacheObject(RivuDataContext.SystemParamEnum.USERAUTHCLASS.toString(), orgi) ;
		if(clazz!= null && clazz.indexOf("UM")>=0){
			modelView.addObject("isUm","um");
		}else{
			modelView.addObject("isUm","r3inner");
		}
    	DetachedCriteria criteria = DetachedCriteria.forClass(UserOrgan.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("organid","0"));
    	modelView = page(request, orgi, modelView, criteria, "beginNum", "endNum", "userorganList");
    	modelView.addObject("parentid","0");
    	return modelView;
    }
    
    @RequestMapping(value="/list/{parentid}" , name="index" , type="manage",subtype="account")
    public ModelAndView index(HttpServletRequest request , @PathVariable String orgi,@PathVariable String parentid , @ModelAttribute RequestData data) throws Exception{ 
    	ModelAndView modelView = request(super.createManageTempletResponse("/pages/manage/account/index") , orgi) ;
    	modelView.addObject("organList", super.getService().findAllByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("orgi",orgi)))) ;
    	DetachedCriteria criteria = DetachedCriteria.forClass(UserOrgan.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("organid",parentid));
    	String username = request.getParameter("username");
    	if(!StringUtils.isBlank(username)){
    		criteria.createCriteria("user").add(Restrictions.like("username", username,MatchMode.ANYWHERE).ignoreCase());
    		modelView.addObject("username",username);
    	}
    	String clazz = (String) CacheHelper.getDistributedDictionaryCacheBean().getCacheObject(RivuDataContext.SystemParamEnum.USERAUTHCLASS.toString(), orgi) ;
		if(clazz!=null && clazz.indexOf("UM")>=0){
			modelView.addObject("isUm","um");
		}else{
			modelView.addObject("isUm","r3inner");
		}
    	modelView = page(request, orgi, modelView, criteria, "beginNum", "endNum", "userorganList");
//    	modelView.addObject("userorganList", super.getService().findAllByCriteria(DetachedCriteria.forClass(UserOrgan.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("organid",parentid)) )) ;
    	
    	modelView.addObject("parentid",parentid);
    	return modelView;
    }
    
    @RequestMapping(value="/userlist/{organid}", name="userlist" , type="manage",subtype="account")  
    public ModelAndView userlist(HttpServletRequest request , @PathVariable String orgi,@PathVariable String organid){  
    	ResponseData responseData = new ResponseData("/pages/manage/role/userlist") ; 
    	ModelAndView modelView = request(responseData , orgi);
    	modelView.addObject("userorgans",super.getService().findAllByCriteria(DetachedCriteria.forClass(UserOrgan.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("organid",organid))));
    	return modelView; 
    }
    
    @RequestMapping(value="/userlistradio/{organid}", name="userlistradio" , type="manage",subtype="account")  
    public ModelAndView userlistradio(HttpServletRequest request , @PathVariable String orgi,@PathVariable String organid){  
    	ResponseData responseData = new ResponseData("/pages/manage/task/userlist") ; 
    	ModelAndView modelView = request(responseData , orgi);
    	modelView.addObject("userorgans",super.getService().findAllByCriteria(DetachedCriteria.forClass(UserOrgan.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("organid",organid))));
    	return modelView; 
    }
    
    @RequestMapping(value="/organadd/{parentid}", name="organadd" , type="manage",subtype="account")  
    public ModelAndView organadd(HttpServletRequest request , @PathVariable String orgi,@PathVariable String parentid){  
    	ResponseData responseData = new ResponseData("/pages/manage/account/organadd") ; 
    	ModelAndView modelView = request(responseData , orgi);
    	Organ organ = null;
    	if(!"0".equals(parentid)){
    		organ = (Organ)super.getService().getIObjectByPK(Organ.class, parentid);
    	}else{
    		organ = new Organ();
    		organ.setId("0");
    		organ.setName("用户分组");
    	}
    	modelView.addObject("organ",organ);
    	return modelView; 
    }
    
    @RequestMapping(value="/organedit/{id}", name="organedit" , type="manage",subtype="account")  
    public ModelAndView organedit(HttpServletRequest request , @PathVariable String orgi,@PathVariable String id){  
    	ResponseData responseData = new ResponseData("/pages/manage/account/organedit") ; 
    	ModelAndView modelView = request(responseData , orgi);
    	Organ organ = (Organ)super.getService().getIObjectByPK(Organ.class, id);
    	if ("0".equals(organ.getParentid())){
    		modelView.addObject("name","用户分组");
    	} else {
	    	Organ organ1 = (Organ)super.getService().getIObjectByPK(Organ.class, organ.getParentid());
	    	modelView.addObject("name",organ1.getName());
    	}
    	modelView.addObject("organ",organ);
    	modelView.addObject("organList", super.getService().findAllByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.ne("id", id)))) ;
    	return modelView; 
    }
    
    /**
     * 添加分组
     * @param request
     * @param orgi
     * @param organ
     * @return
     */
    @RequestMapping(value="/organaddo", method=RequestMethod.POST)  
    public ModelAndView organaddo(HttpServletRequest request , @PathVariable String orgi, @Valid Organ organ){
    	ResponseData responseData = new ResponseData("") ;
    	int count = 0;
    	count = super.getService().getCountByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("parentid",organ.getParentid())).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("name",organ.getName())));
    	if(count>0){
    		responseData.setPage(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(organ.getParentid()).append(".html?msgcode=E_MANAGE_10010019").toString());
    	}else{
    		organ.setOrgi(orgi);
        	organ.setCreatetime(new Date());
        	organ.setCreater(super.getUser(request).getId());
        	super.getService().saveIObject(organ);
        	responseData.setPage(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(organ.getId()).append(".html?msgcode=S_MANAGE_10010001").toString());
    	}
    	
    	ModelAndView modelView = request(responseData , orgi);
        return request(responseData , orgi) ;
    } 
    
    /**
     * 模板下载
     * @param request
     * @param orgi
     * @param code
     * @return
     */
    @RequestMapping(value="/templateexport/{code}" , name="templateexport" , type="manage",subtype="account")
    public ModelAndView templateexport(HttpServletRequest request  ,HttpServletResponse response, @PathVariable String orgi, @PathVariable String code){
    	response.setContentType("charset=UTF-8;application/msexcel");   
		response.addHeader("Content-Disposition","attachment;filename="+code+".xls"); 
		//先暂时这么实现，后续优化
		String clazz = (String) CacheHelper.getDistributedDictionaryCacheBean().getCacheObject(RivuDataContext.SystemParamEnum.USERAUTHCLASS.toString(), orgi) ;
		if("usertemplate".equals(code)){
			code = clazz.indexOf("UM")>=0?code+"_um":code;
		}
		
		String filepath = RivuDataContext.DATA_DIR+File.separatorChar+"template"+File.separatorChar+code+".xls";
		BufferedInputStream is  = null;
		try{
			is = new BufferedInputStream(new FileInputStream(new File(filepath)));
			byte[] buffer = new byte[1024];
			while(is.read(buffer) >0){
				response.getOutputStream().write(buffer);
			}
			response.getOutputStream().flush();
		}catch(Exception ce){
			logger.error("模板导出失败，错误信息为："+ce.getMessage(), ce);
		}finally{
			if(is!=null){
        		try {
					is.close();
				} catch (IOException e) {
					logger.error("关闭流错误，"+e.getMessage(),e);
					
				}
        	}
		}
    	return null;
    }
    
    
    
    
    
    @RequestMapping(value="/userimport/{id}" , name="userimport" , type="manage",subtype="account")
    public ModelAndView userimport(HttpServletRequest request , @PathVariable String orgi, @PathVariable String id){  
    	ResponseData responseData = new ResponseData("/pages/manage/account/userimport") ; 
    	ModelAndView modelView = request(responseData , orgi);
    	modelView.addObject("prarentid",id);
    	return modelView;
    }
    
    
    /**
     * 用户数据导入
     * @param request
     * @param orgi
     * @param file
     * @param id
     * @return
     */
    @RequestMapping(value="/userimportdo/{id}" , name="userimportdo" , type="manage",subtype="account")
    public ModelAndView userimportdo(HttpServletRequest request , @PathVariable String orgi,    @RequestParam MultipartFile file , @PathVariable String id)throws Exception{
    	List<String> users = null;
    	try{
    		String clazz = (String) CacheHelper.getDistributedDictionaryCacheBean().getCacheObject(RivuDataContext.SystemParamEnum.ACCOUNTSERVICECLASS.toString(), orgi) ;
    		AccountService accountService =  (AccountService)Class.forName(clazz).newInstance();
    		users = accountService.importuser(file.getInputStream(),super.getUser(request));
    	}catch(Exception ce){
    		logger.error("用户导入异常，错误信息为:"+ce.getMessage(),ce);
    	}
    	ModelAndView modelView = this.index(request, orgi, null);
    	if(users.size()>0){
    		modelView.addObject("faild_users", users);
    	}
    	
    	modelView.addObject("successfulMsg", LocalTools.getMessage("U_IMPORT_10000001"));
    	return modelView;
    }
    
    
    
    @RequestMapping(value="/umuseradd/{parentid}", name="umuseradd" , type="manage",subtype="account")  
    public ModelAndView umuseradd(HttpServletRequest request , @PathVariable String orgi,@PathVariable String parentid){
    	ResponseData responseData = new ResponseData("/pages/manage/account/umuseradd") ; 
    	ModelAndView modelView = request(responseData , orgi);
    	modelView.addObject("parentid",parentid);
    	return modelView; 
    }
    
    @RequestMapping(value="/umuseraddo", name="umuseraddo" , type="manage",subtype="account")  
    public ModelAndView umuseraddo(HttpServletRequest request , @PathVariable String orgi, @Valid User user,@Valid String organid)throws Exception{  
    	ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(organid).append(".html?msgcode=S_MANAGE_10010004").toString()) ; 
     	int count = 0;
     	User u = UserAuthzFactory.getInstance(orgi).getUser(user.getUsername(), orgi);
     	
     	if(u==null){
     		responseData.setPage(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(organid).append(".html?msgcode=E_MANAGE_10010041").toString());	
     	}else{
     		count = super.getService().getCountByCriteria(DetachedCriteria.forClass(User.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("username",u.getUsername())));
         	if(count>0){//用户名已存在添加失败
         		responseData.setPage(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(organid).append(".html?msgcode=E_MANAGE_10010021").toString());
         	}else{
         		
        		//System.out.println("9090909"+umUser.getUsername());
         		
         		u.setPassword(RivuTools.md5(user.getPassword()));
             	u.setCreater(super.getUser(request).getId());
             	u.setCreatetime(new Date());
             	u.setOrgi(orgi);
             	u.setMobile(user.getMobile()) ;
             	super.getService().saveIObject(u);
             	//默认没有分组建立一个为零的关系（也就是在默认组里）
             	UserOrgan ou = new UserOrgan();
             	ou.setOrganid(organid);
             	ou.setUserid(u.getId());
             	ou.setOrgi(orgi);
             	super.getService().saveIObject(ou);
         	}
     		
     	}
     	
     	
     	ModelAndView modelView = request(responseData , orgi);
         return modelView ;
    }

    
    /**
     * 删除分组
     * @param request
     * @param orgi
     * @param organ
     * @return
     */
    @RequestMapping(value="/organdelo/{id}" , name="index" , type="manage",subtype="account")
    public ModelAndView organdelo(HttpServletRequest request , @PathVariable String orgi, @PathVariable String id){  
    	ResponseData responseData = new ResponseData("redirect:/{orgi}/manage/account/index.html?msgcode=S_MANAGE_10010002") ;
    	
    	List<Organ> children = super.getService().findPageByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("parentid",id))) ;
    	List<UserOrgan> users = super.getService().findPageByCriteria(DetachedCriteria.forClass(UserOrgan.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("organid",id))) ;
    	if(children.size()>0||users.size()>0){
    		responseData.setPage(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(id).append(".html?msgcode=E_MANAGE_10010012").toString());
    	}else{
    		super.getService().deleteIObject(super.getService().getIObjectByPK(Organ.class, id));
    	}
    	
    	ModelAndView modelView = request(responseData , orgi);
        return modelView ;
    } 
    
    /**
     * 编辑分组
     * @param request
     * @param orgi
     * @param organ
     * @return
     */
    @RequestMapping(value="/organedito", method=RequestMethod.POST)  
    public ModelAndView organedito(HttpServletRequest request , @PathVariable String orgi, @Valid Organ organ){  
        ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(organ.getId()).append(".html?msgcode=S_MANAGE_10010003").toString()) ;
        Organ org =(Organ)super.getService().getIObjectByPK(Organ.class, organ.getId());
        
    	int count = 0;
    	count = super.getService().getCountByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("parentid",organ.getParentid())).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("name",organ.getName())));
    	if(!org.getName().equals(organ.getName())&&count>0){
    		responseData.setPage(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(organ.getId()).append(".html?msgcode=E_MANAGE_10010020").toString());
    	}else{
        	org.setName(organ.getName());
        	org.setCode(organ.getCode());
        	org.setParentid(organ.getParentid());
        	org.setUpdatetime(new Date());
        	super.getService().saveOrUpdateIObject(org);
    	}
    	
    	ModelAndView modelView = request(responseData , orgi);
        return request(responseData , orgi) ;
    } 
    
    @RequestMapping(value="/useradd/{parentid}", name="useradd" , type="manage",subtype="account")  
    public ModelAndView useradd(HttpServletRequest request , @PathVariable String orgi,@PathVariable String parentid){  
    	ResponseData responseData = new ResponseData("/pages/manage/account/useradd") ; 
    	ModelAndView modelView = request(responseData , orgi);
    	modelView.addObject("parentid",parentid);
    	modelView.addObject("organList", super.getService().findPageByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("orgi",orgi)))) ;
    	return modelView; 
    }
    
    @RequestMapping(value="/{organid}/useredit/{id}", name="useredit" , type="manage",subtype="account")  
    public ModelAndView useredit(HttpServletRequest request , @PathVariable String organid, @PathVariable String orgi,@PathVariable String id){  
    	ResponseData responseData = new ResponseData("/pages/manage/account/useredit") ; 
    	ModelAndView modelView = request(responseData , orgi);
    	User n_user = (User)super.getService().getIObjectByPK(User.class, id);
    	modelView.addObject("n_user",n_user);
    	modelView.addObject("organid",organid);
    	
    	modelView.addObject("organList", super.getService().findAllByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("orgi",orgi)))) ;
    	return modelView; 
    }
    
    @RequestMapping(value="/updateuser/{id}", name="updateuser" , type="manage",subtype="account")  
    public ModelAndView updateuser(HttpServletRequest request , @PathVariable String orgi,@PathVariable String id,@Valid String url){  
    	ResponseData responseData = new ResponseData("/pages/manage/account/useredit") ; 
    	ModelAndView modelView = request(responseData , orgi);
    	User n_user = (User)super.getService().getIObjectByPK(User.class, id);
    	modelView.addObject("n_user",n_user);
    	if(url != null){
    		modelView.addObject("url", url);
    	}
    	modelView.addObject("organList", super.getService().findAllByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("orgi",orgi)))) ;
    	return modelView; 
    }
    
    /**
     * 修改用户
     * @param request
     * @param orgi
     * @param user
     * @return
     */
    @RequestMapping(value="/updateuserdo", method=RequestMethod.POST)  
    public ModelAndView updateuserdo(HttpServletRequest request , @PathVariable String orgi, @Valid User user,@Valid String url){ 
    	
    	ResponseData responseData = new ResponseData("redirect:"+url+"?msgcode=S_MANAGE_10010005") ; 
    	User u = (User)super.getService().getIObjectByPK(User.class, user.getId());
    	int count = 0;
    	int email_count = 0;
    	count = super.getService().getCountByCriteria(DetachedCriteria.forClass(User.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("username",user.getUsername())));
    	email_count = super.getService().getCountByCriteria(DetachedCriteria.forClass(User.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("email",user.getEmail())));
    	if(!u.getUsername().equals(user.getUsername())&&count>0){//用户名已存在添加失败
    		responseData.setPage(new StringBuffer().append("redirect:").append(url).append("?msgcode=E_MANAGE_10010023").toString());
    	}else if(u.getEmail() != null && !u.getEmail().equals(user.getEmail())&&email_count>0){
    		responseData.setPage(new StringBuffer().append("redirect:").append(url).append("?msgcode=E_MANAGE_10010024").toString());
    	}else{
    		if(!"".equals(user.getPassword())){
        		u.setPassword(RivuTools.md5(user.getPassword()));
        	}
        	u.setUpdatetime(new Date());
        	u.setEmail(user.getEmail());
        	u.setFirstname(user.getFirstname());
        	u.setUsername(user.getUsername());
        	u.setLastname(user.getLastname());
        	u.setNickname(user.getNickname());
        	u.setBirthday(user.getBirthday());
        	u.setDepartment(user.getDepartment());
        	//u.setOrgan(user.getOrgan());
        	u.setMemo(user.getMemo());
        	super.getService().saveOrUpdateIObject(u);
    	}
    	
    	ModelAndView modelView = request(responseData , orgi);
        return modelView ;
    } 
    
    /**
     * 添加用户
     * @param request
     * @param orgi
     * @param user
     * @return
     */
    @RequestMapping(value="/useraddo", method=RequestMethod.POST)  
    public ModelAndView useraddo(HttpServletRequest request , @PathVariable String orgi, @Valid User user,@Valid String organid){  
        ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(organid).append(".html?msgcode=S_MANAGE_10010004").toString()) ; 
    	int count = 0;
    	int email_count = 0;
    	count = super.getService().getCountByCriteria(DetachedCriteria.forClass(User.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("username",user.getUsername())));
    	email_count = super.getService().getCountByCriteria(DetachedCriteria.forClass(User.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("email",user.getEmail())));
    	if(count>0){//用户名已存在添加失败
    		responseData.setPage(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(organid).append(".html?msgcode=E_MANAGE_10010021").toString());
    	}else if(email_count>0){
    		responseData.setPage(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(organid).append(".html?msgcode=E_MANAGE_10010022").toString());
    	}else{
    		user.setPassword(RivuTools.md5(user.getPassword()));
        	user.setCreater(super.getUser(request).getId());
        	user.setCreatetime(new Date());
        	user.setPassupdatetime(new Date());
        	user.setUpdatetime(new Date());
        	user.setOrgi(orgi);
        	super.getService().saveIObject(user);
        	//默认没有分组建立一个为零的关系（也就是在默认组里）
        	UserOrgan ou = new UserOrgan();
        	ou.setOrganid(organid);
        	ou.setUserid(user.getId());
        	ou.setOrgi(orgi);
        	super.getService().saveIObject(ou);
    	}
    	
    	ModelAndView modelView = request(responseData , orgi);
        return modelView ;
    } 
    
    /**
     * 删除用户
     * @param request
     * @param orgi
     * @param organ
     * @return
     */
    @RequestMapping(value="/{organid}/userdelo/{id}" , name="index" , type="manage",subtype="account")
    public ModelAndView userdelo(HttpServletRequest request , @PathVariable String orgi, @PathVariable String id, @PathVariable String organid)throws Exception{  
    	ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(organid).append(".html?msgcode=S_MANAGE_10010006").toString()) ; 
    	int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(UserOrgan.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("userid",id)));
    	if(count>1){
    		List<UserOrgan> uos = super.getService().findAllByCriteria(DetachedCriteria.forClass(UserOrgan.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("organid",organid)).add(Restrictions.eq("userid",id)));
    		if(uos.size()>0){
    			super.getService().deleteIObject(uos.get(0));
    		}
    	}else{
    		super.getService().execByHQL("delete from UserRole where userid='"+id+"' and orgi='"+orgi+"'");//删除角色关联
    		super.getService().execByHQL("delete from Auth where ownerid='"+id+"' and ownertype='3' and orgi='"+orgi+"'");//删除用户的权限数据
    		super.getService().deleteIObject(super.getService().getIObjectByPK(User.class, id));
    		
    	}
    	ModelAndView modelView = request(responseData , orgi);
    	
        return modelView;
    }
    /**
     * 修改用户
     * @param request
     * @param orgi
     * @param user
     * @return
     */
    @RequestMapping(value="/{organid}/useredito", method=RequestMethod.POST)  
    public ModelAndView useredito(HttpServletRequest request , @PathVariable String orgi,@PathVariable String organid, @Valid User user){ 
    	
    	ResponseData responseData = new ResponseData("redirect:/{orgi}/manage/account/list/{organid}.html?msgcode=S_MANAGE_10010005") ; 
    	User u = (User)super.getService().getIObjectByPK(User.class, user.getId());
    	int count = 0;
    	int email_count = 0;
    	count = super.getService().getCountByCriteria(DetachedCriteria.forClass(User.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("username",user.getUsername())));
    	email_count = super.getService().getCountByCriteria(DetachedCriteria.forClass(User.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("email",user.getEmail())));
    	if(!u.getUsername().equals(user.getUsername())&&count>0){//用户名已存在添加失败
    		responseData.setPage(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(organid).append(".html?msgcode=E_MANAGE_10010023").toString());
    	}else if(u.getEmail()!=null&&!u.getEmail().equals(user.getEmail())&&email_count>0){
    		responseData.setPage(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(organid).append(".html?msgcode=E_MANAGE_10010024").toString());
    	}else{
    		if(!"".equals(user.getPassword())){
        		u.setPassword(RivuTools.md5(user.getPassword()));
        		u.setPassupdatetime(new Date());
        	}
    		
        	u.setUpdatetime(new Date());
        	u.setEmail(user.getEmail());
        	u.setFirstname(user.getFirstname());
        	u.setUsername(user.getUsername());
        	u.setLastname(user.getLastname());
        	u.setNickname(user.getNickname());
        	u.setBirthday(user.getBirthday());
        	u.setDepartment(user.getDepartment());
        	u.setMobile(user.getMobile()) ;
        	//u.setOrgan(user.getOrgan());
        	u.setMemo(user.getMemo());
        	super.getService().saveOrUpdateIObject(u);
    	}
    	if(organid==null){//如果是点击首页的修改用户连接跳转到首页
    		String pg = responseData.getPage();
    		responseData.setPage("redirect:/{orgi}/user/index"+pg.substring(pg.indexOf(".html")));
    	}
    	ModelAndView modelView = request(responseData , orgi);
        return modelView ;
    } 
    
    /**
     * 修改用户
     * @param request
     * @param orgi
     * @param user
     * @return
     */
    @RequestMapping(value="/{organid}/{userid}/resetpasswordo", name="resetpasswordo" , type="manage",subtype="account")  
    public ModelAndView resetpasswordo(HttpServletRequest request , @PathVariable String orgi,@PathVariable String organid, @PathVariable String userid){ 
    	
    	ResponseData responseData = new ResponseData("redirect:/{orgi}/manage/account/list/{organid}.html?msgcode=S_MANAGE_100100065") ; 
    	User u = (User)super.getService().getIObjectByPK(User.class,userid);
    	u.setPassword(RivuTools.md5("123456"));
    	super.getService().updateIObject(u);
    	ModelAndView modelView = request(responseData , orgi);
        return modelView ;
    } 
    
    @RequestMapping(value="/usercopy", name="usercopy" , type="manage",subtype="account")  
    public ModelAndView usercopy(HttpServletRequest request , @PathVariable String orgi){  
    	ResponseData responseData = new ResponseData("/pages/manage/account/usercopy") ; 
    	ModelAndView modelView = request(responseData , orgi);
    	modelView.addObject("organList", super.getService().findPageByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("orgi",orgi)))) ;
    	return modelView; 
    }
    
    @RequestMapping(value="/usermove", name="usermove" , type="manage",subtype="account")  
    public ModelAndView usermove(HttpServletRequest request , @PathVariable String orgi){  
    	ResponseData responseData = new ResponseData("/pages/manage/account/usermove") ; 
    	ModelAndView modelView = request(responseData , orgi);
    	modelView.addObject("organList", super.getService().findPageByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("orgi",orgi)))) ;
    	return modelView; 
    }
    
    @RequestMapping(value="/usercopylist", method=RequestMethod.POST)  
    public ModelAndView usercopylist(HttpServletRequest request , @PathVariable String orgi, @Valid String[] userid, @Valid String organid){  
    	ResponseData responseData = new ResponseData("redirect:/{orgi}/manage/account/index.html?msgcode=S_MANAGE_10010007") ; 
    	
    	if(userid!=null){
    		UserOrgan uo = null;
    		List<UserOrgan> uos = null;
    		int count = 0 ;
    		boolean flag = true;
    		for (int i = 0; i < userid.length; i++) {
    			count = super.getService().getCountByCriteria(DetachedCriteria.forClass(UserOrgan.class).add(Restrictions.eq("organid",organid)).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("userid",userid[i])));
				if(count>0){
					flag=false;
					break;
				}
			}
    		if(flag){
    			for (int i = 0; i < userid.length; i++) {
    				uo = new UserOrgan();
					uo.setOrganid(organid);
					uo.setUserid(userid[i]);
					uo.setOrgi(orgi);
					super.getService().saveIObject(uo);
				}
    		}else{
    			responseData.setPage("redirect:/{orgi}/manage/account/index.html?msgcode=E_MANAGE_10010010");
    		}
    	}
    	ModelAndView modelView = request(responseData , orgi);
        return modelView;
    } 
    @RequestMapping(value="/usermovelist", method=RequestMethod.POST)  
    public ModelAndView usermovelist(HttpServletRequest request , @PathVariable String orgi, @Valid String[] userid, @Valid String organid,@Valid String old_organid){  
    	ResponseData responseData = new ResponseData("redirect:/{orgi}/manage/account/index.html?msgcode=S_MANAGE_10010008") ; 
    	
    	if(userid!=null){
    		UserOrgan uo = null;
    		List<UserOrgan> uos = null;
    		int count = 0 ;
    		boolean flag = true;
    		for (int i = 0; i < userid.length; i++) {
    			count = super.getService().getCountByCriteria(DetachedCriteria.forClass(UserOrgan.class).add(Restrictions.eq("organid",organid)).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("userid",userid[i])));
				if(count>0){
					flag=false;
					break;
				}
			}
    		if(flag){
    			for (int i = 0; i < userid.length; i++) {
    				uos = super.getService().findAllByCriteria(DetachedCriteria.forClass(UserOrgan.class).add(Restrictions.eq("organid",old_organid)).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("userid",userid[i])));
    				if(uos.size()>0){
    					uo = uos.get(0);
    					uo.setOrganid(organid);
    					uo.setUserid(userid[i]);
    					super.getService().saveOrUpdateIObject(uo);
    				}
					
				}
    		}else{
    			responseData.setPage("redirect:/{orgi}/manage/account/index.html?msgcode=E_MANAGE_10010011");
    		}
    	}
    	ModelAndView modelView = request(responseData , orgi);
        return modelView;
    } 
    @RequestMapping(value="/userdellist", method=RequestMethod.POST)  
    public ModelAndView userdellist(HttpServletRequest request , @PathVariable String orgi, @Valid String[] userid,@Valid String old_organid)throws Exception{  
    	ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/account/list/").append(old_organid).append(".html?msgcode=S_MANAGE_10010009").toString()) ; 
    	if(userid!=null){
    		UserOrgan uo = null;
    		List<UserOrgan> uos = null;
    		int count = 0 ;
    		for (int i = 0; i < userid.length; i++) {
    			
		    	super.getService().execByHQL("delete from UserOrgan where userid='"+userid[i]+"' and organid='"+old_organid+"' and orgi='"+orgi+"'");

		    	super.getService().deleteIObject(super.getService().getIObjectByPK(User.class, userid[i]));
			}
    	}
    	ModelAndView modelView = request(responseData , orgi);
        return modelView;
    } 
    
    /**
     * 根据用户Id查询到用户的个人报表信息
     * @param request
     * @param orgi
     * @param userid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/userreportlist/{parentid}", name="userreportlist", type="manage", subtype="account")
    public ModelAndView userreportlist(HttpServletRequest request , @PathVariable String orgi, @Valid String userid,@PathVariable String parentid) throws Exception{
    	ResponseData responseData = new ResponseData("/pages/manage/account/userreport") ; 
    	ModelAndView view = request(responseData , orgi) ;
    	//根据userid获取用户信息
    	try {
			User user = (User) super.getService().getIObjectByPK(User.class, userid);
			List<PublishedReport> reportList =  ReportFactory.getReportInstance().getReportList(parentid, orgi , user , "pri",null);
			view.addObject("dicList", ReportFactory.getReportInstance().getAllReportDicList(orgi , user , "pri"));
			view.addObject("reportList",reportList) ;
			view.addObject("parentid", parentid);
			view.addObject("userid", userid);
			view.addObject("user", user);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return view;
    }
    
    @RequestMapping(value="/{parentid}/{reportid}/{userid}/reportdelo" , name="reportdelo" , type="user" , subtype="public")  
    public ModelAndView reportdelo(HttpServletRequest request , @PathVariable String orgi , 
    		@PathVariable String parentid,@PathVariable String reportid,@PathVariable String userid) throws ReportException{  
		ResponseData responseData = new ResponseData("redirect:/{orgi}/manage/account/userreportlist/{parentid}.html?msgcode=S_REPORT_10010008&userid="+userid) ;
		ReportFactory.getReportInstance().rmReportByID(reportid, super.getUser(request), orgi);
		ModelAndView view = request(responseData , orgi) ;
		return view; 
    }
    
} 